import { BaseReactElementState, BaseReactElement, reactControl, BaseReactElementControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { WhiteSpace, Card, ListView, NavBar, Toast, Modal } from "antd-mobile";
// import { Icon } from 'antd';
import { Row, Col, Icon, Button, } from "antd";
// import { News } from "src/projects/models/news";
import { AppServiceUtility } from "src/projects/app/appService";
import { request } from "src/business/util_tool";
// import moment from "moment";
import { getAppPermissonObject, ROUTE_PATH } from "src/projects/app/util-tool";
import './index.less';
import { IntelligentElderlyCareAppStorage } from "src/projects/app/appStorage";
import { LOCAL_FUNCTION_LIST } from "src/business/mainForm/backstageManageMainForm";
// import Input from "antd-mobile/lib/input-item/Input";
// import { CommentEdit } from "src/business/components/buss-components/comment-edit/index";
// const Item = List.Item;
// const Brief = Item.Brief;

// function MyBody(props: any) {
//     return (
//         <Row className="am-list-body my-body" style={{ height: '100%' }}>
//             {props.children}
//         </Row>
//     );
// }

const prompt = Modal.prompt;
/**
 * 组件：新闻详情页面状态
 */
export interface NewsInfoViewState extends BaseReactElementState {
    /** 数据 */
    data: any;
    /** 长列表数据 */
    dataSource?: any;
    /** 图片高度 */
    imgHeight?: number | string;
    /** 评论列表 */
    comment_list?: any[];
    /** 长列表容器高度 */
    height?: any;
    /** 评论内容 */
    comment_value?: any;
    focusState?: any;
    // user信息
    user?: any;

    // 
    code?: any;
    // 是否拥有审核权限
    isAudit?: boolean;
    is_send?: boolean;

    is_likes?: boolean;
    is_share?: boolean;

    likes_count?: number;
    share_count?: number;
}

/**
 * 组件：新闻详情页面
 * 新闻详情
 */
export class NewsInfoView extends BaseReactElement<NewsInfoViewControl, NewsInfoViewState> {
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            data: {},
            imgHeight: 176,
            comment_list: [],
            dataSource: ds,
            height: document.documentElement!.clientHeight,
            comment_value: '',
            focusState: true,
            user: [],
            code: '',
            isAudit: false,
            is_send: false,
            is_likes: false,
            is_share: false,
            likes_count: 0,
            share_count: 0,
        };
    }

    componentDidMount() {
        this.setState({ user: IntelligentElderlyCareAppStorage.getCurrentUser() });
        let id = this.props.match!.params.key;
        request(this, AppServiceUtility.person_org_manage_service.check_permission!({ 'method': 'audit', 'type': 'article' }))
            .then((data: any) => {
                if (data.code === 'Success') {
                    this.setState({
                        isAudit: data.isAudit,
                    });
                }
            });
        let param: any = { 'id': id };
        if (this.props.match!.params.code && this.props.match!.params.code === 'SH') {
            param['all'] = true;
        }
        request(this, AppServiceUtility.article_list_service.get_news_list!(param))
            .then((data: any) => {
                if (data && data.result && data.result.length > 0) {
                    this.setState({
                        data: data.result[0],
                        is_likes: data.result[0]['is_likes'] === 1 ? true : false,
                        is_share: data.result[0]['is_share'] === 1 ? true : false,
                        likes_count: data.result[0]['likes_count'],
                        share_count: data.result[0]['share_count'],
                    });
                }
            });
        AppServiceUtility.comment_service.get_comment_list_all!({ 'comment_object_id': id }, 1, 9999)!
            .then((data: any) => {
                let comment_list: any[] = [];
                if (data) {
                    comment_list = data.result.map((key: any, value: any) => {
                        let comment = {};
                        comment['id'] = key['id'];
                        comment['content'] = key['content'];
                        comment['comment_date'] = key['comment_date'];
                        comment['like_list'] = key.like_list;
                        comment['comment_user'] = key['comment_user'];
                        return comment;
                    });
                    this.setState(
                        { comment_list }
                    );
                }
            });
    }

    onClickRow = (id: string) => {
        this.props.history!.push(ROUTE_PATH.childCommmentList + '/' + id);
    }
    commentChange = (e: any) => {
        this.setState({
            comment_value: e.target.value
        });
    }
    textAreaChange = (value: any) => {
        this.setState({
            comment_value: value
        });
    }
    commentsubmit = () => {
        let id = this.props.match!.params.key;
        let comment = { 'comment_object_id': id, 'content': this.state.comment_value, 'type_id': this.state.data.type_id };
        if (this.state.comment_value !== '') {
            request(this, AppServiceUtility.comment_service.update_comment!(comment))
                .then((data: any) => {
                    if (data) {
                        this.setState({
                            comment_value: ''
                        });
                        AppServiceUtility.comment_service.get_comment_list_all!({ 'comment_object_id': id }, 1, 9999)!
                            .then((data: any) => {
                                let comment_list: any[] = [];
                                if (data) {
                                    comment_list = data.result.map((key: any, value: any) => {
                                        let comment = {};
                                        comment['id'] = key['id'];
                                        comment['content'] = key['content'];
                                        comment['comment_date'] = key['comment_date'];
                                        comment['like_list'] = key.like_list;
                                        comment['comment_user'] = key['comment_user'];
                                        return comment;
                                    });
                                    this.setState(
                                        { comment_list }
                                    );
                                }
                            });
                    }
                });
        }
        // AppServiceUtility.comment_service.update_comment!(comment)!
        //     .then((data: any) => {
        //         if (data) {

        //         }
        //     });
    }
    /** input框获得焦点 */
    inputChange = () => {
        this.setState({
            focusState: !this.state.focusState
        });
    }
    ctrlThis(type: string) {
        let data_info = this.state.data;
        let { is_likes, likes_count, share_count, is_send } = this.state;
        let param: any = { id: data_info['id'], type: type };
        let is_cancel = false;
        if (is_send === true) {
            return;
        }
        if (is_likes === true && type === 'likes') {
            is_cancel = true;
        }
        this.setState(
            {
                is_send: true,
            },
            () => {
                if (data_info && data_info.hasOwnProperty('id')) {
                    request(this, AppServiceUtility.article_list_service.update_ctrl!(param))
                        .then((data: any) => {
                            if (data === 'Success') {
                                if (type === 'likes') {
                                    if (is_cancel) {
                                        Toast.success('取消成功 ！');
                                        this.setState({
                                            is_likes: false,
                                            is_send: false,
                                            likes_count: likes_count! - 1,
                                        });
                                    } else {
                                        Toast.success('点赞成功 ！');
                                        this.setState({
                                            is_likes: true,
                                            is_send: false,
                                            likes_count: likes_count! + 1,
                                        });
                                    }
                                } else if (type === 'share') {
                                    if (is_cancel) {
                                        Toast.success('取消成功 ！');
                                        this.setState({
                                            is_share: false,
                                            is_send: false,
                                            share_count: share_count! - 1,
                                        });
                                    } else {
                                        Toast.success('分享成功 ！');
                                        this.setState({
                                            is_share: true,
                                            is_send: false,
                                            share_count: share_count! + 1,
                                        });
                                    }
                                }
                            } else {
                                Toast.fail(data);
                            }
                        }).catch((error: Error) => {
                            console.error(error.message);
                        });
                }
            }
        );
    }
    auditOpen() {
        prompt('资讯审核', '', [
            {
                text: '不通过',
                onPress: value => {
                    this.auditThis('不通过', value);
                },
            },
            {
                text: '通过',
                onPress: value => {
                    this.auditThis('通过', value);
                },
            }]);
    }
    auditThis(type: string, value: string = '') {
        let { data } = this.state;
        if (type === '不通过' && value === '') {
            Toast.info('不通过请填写原因！');
            return;
        }
        let param: any = {
            // 审批标识
            'is_sp': 1,
            // 审批状态
            'sp_status': type,
            // 主数据状态
            'status': type,
            // 审批信息
            'sp_msg': value,
            // 步骤
            'step_no': 2,
            // 主键ID
            'id': data['id'],
        };
        const is_send = this.state.is_send;
        const that = this;
        // 正在发送请求
        if (is_send === true) {
            Toast.fail('请勿操作过快！');
            return;
        }
        this.setState(
            {
                is_send: true,
            },
            () => {
                request(that, AppServiceUtility.article_list_service.update_news!(param))
                    .then((data: any) => {
                        if (data === 'Success') {
                            Toast.success('操作成功！', 3, () => history.back());
                        } else {
                            Toast.fail(data);
                        }
                    }).catch((error: Error) => {
                        Toast.fail(error.message);
                    });
            }
        );
        return;
    }
    render() {
        let { data, user, isAudit, likes_count, share_count, is_likes, is_share } = this.state;
        const AppPermission = JSON.parse(localStorage.getItem(LOCAL_FUNCTION_LIST)!);
        // let id = this.props.match!.params.key;
        // let type = this.props.match!.params.code;
        // const comment = (owData: any, sectionID: any, rowID: any) => {
        //     return (
        //         <Row>
        //             <Card>
        //                 <Row type='flex' justify='center' >
        //                     <Col className='list-col' span={3}><WhiteSpace size='sm' /><Avatar size='large' icon="user" /></Col>
        //                     <Col span={20} className='list-col'>
        //                         <WhiteSpace size='sm' />
        //                         <Row>
        //                             <Col span={12}><strong>{owData.comment_user}</strong></Col>
        //                             <Col span={12}>{moment(owData.comment_date).format("YYYY-MM-DD hh:mm")}</Col>
        //                         </Row>
        //                         <Row>
        //                             {owData.content}
        //                         </Row>
        //                     </Col>
        //                 </Row>
        //             </Card>
        //         </Row>
        //     );
        // };
        return (
            <Row>
                <NavBar
                    className={data && data['title'] && data['title'].length > 11 ? "ny-news-info start" : "ny-news-info"}
                    icon={<Icon type={"left"} onClick={() => history.back()} />}
                    rightContent={((user && user['id'] && data && data['promulgator_id'] && user['id'] === data['promulgator_id']) || (AppPermission && getAppPermissonObject(AppPermission, '新闻管理', '编辑'))) ? <Row type="flex" justify="end" onClick={() => this.props.history!.push(ROUTE_PATH.changeNews + '/' + this.props.match!.params.key)}>编辑</Row> : null}
                >
                    {
                        data && data['title'] ? data['title'] : ''
                    }
                </NavBar>
                {/* 轮播图 */}
                {/* <Carousel
                    autoplay={true}
                    infinite={true}
                >
                    {data!.app_img_list ? data!.app_img_list!.map((value: any, index: any) => (
                        <a
                            className='carousel-a'
                            key={index}
                            href="javascript:;"
                            style={{ height: this.state.imgHeight }}
                        >
                            <img
                                className='carousel-img'
                                src={value}
                                alt=""
                                onLoad={() => {
                                    window.dispatchEvent(new Event('resize'));
                                    this.setState({ imgHeight: 'auto' });
                                }}
                            />
                        </a>
                    )) :
                        <a
                            className='carousel-a'
                            key={1}
                            href="javascript:;"
                            style={{ height: this.state.imgHeight }}
                        >
                            <img
                                className='carousel-img'
                                // src={'https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1566444740&di=ef8aa22b538cd90e69a4992b53ecca73&src=http://s6.sinaimg.cn/mw690/6252dd6dgd86a35829e35&690'}
                                alt=""
                                onLoad={() => {
                                    window.dispatchEvent(new Event('resize'));
                                    this.setState({ imgHeight: 'auto' });
                                }}
                            />
                        </a>
                    }
                </Carousel> */}
                {/* <WhiteSpace size="lg" />
                <Card>
                    
                </Card> */}
                <Card>
                    {/* <Row><strong>{data.subhead}</strong></Row> */}
                    {/* <Col className='time' span={10}>
                        <Row>{data.source}</Row>
                    </Col> */}

                    <Card.Body className="newsInfoBox">
                        <Row style={{ textAlign: 'center', fontSize: '20px', fontWeight: 'bold', marginBottom: '20px', }}>
                            {data.title}
                        </Row>
                        <Row className="ny-htmlbody" dangerouslySetInnerHTML={{ __html: data.content! }} />
                    </Card.Body>

                </Card>
                <WhiteSpace size="lg" />
                {/* 评论 */}
                <Row>
                    {/* <Tabs
                    // tabs={tabs}
                    initialPage={0}
                > */}
                    {/* <Card className='list-conten' id="pl">
                        <Card.Header
                            title="评论"
                        />
                        <Row className='tabs-content'>
                            {
                                comment_list && comment_list.length ?
                                    <ListView
                                        ref={el => this['lv'] = el}
                                        dataSource={dataSource.cloneWithRows(comment_list)}
                                        renderRow={comment}
                                        initialListSize={10}
                                        pageSize={10}
                                        renderBodyComponent={() => <MyBody />}
                                        style={{ height: this.state.height }}
                                    />
                                    :
                                    <Row className='tabs-content' type='flex' justify='center'>
                                        暂无评论
                                    </Row>
                            }
                        </Row>
                    </Card> */}
                </Row>
                {/* {
                    this.btn_row(id, type)
                } */}
                {/* {this.state.focusState
                ? <Row className='comment'>
                    <Icon type='left' className='icon-left' onClick={() => {history.back();}} />
                    <Input className='input' value={this.state.comment_value} onChange={this.commentChange} onFocus={this.inputChange}/>
                    <Icon type="profile" className='icon-right'/>
                    <Row className='button' onClick={this.commentsubmit}><span>发送</span></Row>
                </Row>
                : 
                <Row className='comment-textarea'>
                    <TextareaItem
                        className='textarea'
                        autoHeight={true}
                        rows={4}
                        labelNumber={5}
                        onChange={this.textAreaChange}
                        value={this.state.comment_value}
                    />
                    <Row className='send' onClick={this.commentsubmit}>发送</Row>
                </Row>
                } */}
                {/* <CommentEdit inputValue={this.state.comment_value} commentChange={this.commentChange} commentsubmit={this.commentsubmit} textAreaChange={this.textAreaChange} comment_value={this.state.comment_value} /> */}
                <Row
                    style={{
                        position: 'fixed',
                        bottom: '0',
                        width: '100%',
                        height: '50px',
                        background: '#ffffff',
                    }}
                >
                    {isAudit && data.step_no !== undefined && data.step_no !== -1 && data.status !== undefined && data.status !== '不通过' ? <Row style={{ textAlign: 'center', lineHeight: '50px', borderRight: '1px solid #ddd' }}>
                        <Button className="btnW950" type="primary" onClick={() => this.auditOpen()}>审核</Button>
                    </Row> : data.step_no === -1 ? <Row>
                        <Col span={12} style={{ textAlign: 'center', lineHeight: '50px', borderRight: '1px solid #ddd' }}>
                            <span className={is_likes ? 'font-red' : ''} style={{ marginRight: '10px', fontSize: '20px' }} onClick={() => this.ctrlThis('likes')}>
                                <Icon type="like" style={{ marginRight: '5px' }} />点赞：{likes_count || 0}
                            </span>
                        </Col>
                        <Col span={12} style={{ textAlign: 'center', lineHeight: '50px' }}>
                            <span className={is_share ? 'font-red' : ''} style={{ marginRight: '10px', fontSize: '20px' }} onClick={() => this.ctrlThis('share')}>
                                <Icon type="branches" style={{ marginRight: '5px' }} />分享：{share_count || 0}
                            </span>
                        </Col>
                    </Row> : null}
                </Row>
            </Row >
        );
    }
}

/**
 * 控件：新闻详情页面控制器
 * 新闻详情
 */
@addon('NewsInfoView', '新闻详情页面', '新闻详情')
@reactControl(NewsInfoView, true)
export class NewsInfoViewControl extends BaseReactElementControl {
    constructor() {
        super();
    }
}